﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace AudioEffectBox
{
    public class Audio16ModulationStream : Audio16CompositionStream
    {
        protected int _lastModulationSample;
        private int _sampleToSkip;
        private int _modulationSpeed;
        public Audio16ModulationStream(Stream secondaryInput, int modulationLevel, Stream outputStream, int modulationSpeed) : base(secondaryInput,outputStream)
        {
            this.ModulationLevel = modulationLevel;
            _lastModulationSample = modulationLevel;
            this.ModulationSpeed = modulationSpeed;
            this._sampleToSkip = 0;
        }
        public int ModulationLevel { get; set; }
        public int ModulationSpeed { get { return _modulationSpeed; } set { lock (this) { _modulationSpeed = value; _sampleToSkip = 0; } } }

        protected virtual void ProcessSample(Int16 sample)
        {
            if (IsEnabled)
            {
                sample = (Int16)((sample * _lastModulationSample) / ModulationLevel);                
            }
            _writer.Write(sample);
        }


        public override void Write(byte[] buffer, int offset, int count)
        {            
            MemoryStream _buffer = new MemoryStream(buffer, offset, count);
            BinaryReader _reader = new BinaryReader(_buffer);
            int _totalSamples = count / 2;
            lock (this)
            {
                while (_totalSamples != 0)
                {
                    if (_sampleToSkip == 0)
                    {                        
                        _sampleToSkip = ModulationSpeed;
                        _lastModulationSample = _secondReader.ReadInt16();
                    }
                    else
                        if (_sampleToSkip > 0)
                        {
                            while (_sampleToSkip != 0)
                            {
                                _sampleToSkip--;
                                _lastModulationSample = _secondReader.ReadInt16();
                            }
                            _sampleToSkip = ModulationSpeed;
                        }
                        else
                        {
                            _sampleToSkip++;
                        }
                    Int16 _sample = _reader.ReadInt16();
                    ProcessSample(_sample);                        
                    _totalSamples--;
                }
            }
        }
    }
}
